import org.codehaus.groovy.grails.plugins.springsecurity.RedirectUtils
import org.grails.plugins.springsecurity.service.AuthenticateService

import org.springframework.security.AuthenticationTrustResolverImpl
import org.springframework.security.DisabledException
import org.springframework.security.context.SecurityContextHolder as SCH
import org.springframework.security.ui.AbstractProcessingFilter
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter

/**
 * Login Controller (Example).
 */
class LoginController {

	/**
	 * Dependency injection for the authentication service.
	 */
	def authenticateService
 

	private final authenticationTrustResolver = new AuthenticationTrustResolverImpl()

	def index = {
		if (isLoggedIn()) {
			redirect uri: '/layout/welcome'
		}
		else {
			redirect action: auth
		}
	}
// 登录预处理，处理验证码，处理管理员登录，处理不同学校用户的登录信息
    def authBefore = {
//                验证码，检查
           if (params.captcha?.toUpperCase() != session.captcha) {
              flash.message = "验证码错误"
              return render(view: 'auth', model: [postUrl: params.postUrl,remoteUser:params.j_username])
           }
//          
//         清理session
            session.removeAttribute('schoolId' )
            session.removeAttribute('school' )
           // 根据子域名判断学校
           def school = checkDomain()
        
           if(!school){ 
                if (User.countByUsername(params.j_username) > 0) { 
                    return redirect(uri:"/cloud/j_spring_security_check?j_username=${URLEncoder.encode(params.j_username,'UTF-8')}&j_password=${params.j_password}")
                } else{
                    //school = School.get(params.schoolid?.trim())
                    flash.message = "没有找到此学校！"
                    return render(view: 'auth', model: [postUrl: params.postUrl,remoteUser:params.j_username])
                }
           }

           if(new Date() > school.end){
                log.info("有效时间已过")
                flash.message = "此学校的有效时间已过，不能登录！"
                return render(view: 'auth', model: [postUrl: params.postUrl,remoteUser:params.j_username])
           }
           def realUserName = params.j_username+grailsApplication.config.grails.default.username.segment+school.id
           log.info("realUserName=="+realUserName)
           def teacherInstance = Teacher.countBySchoolAndUsername(school,realUserName)
           if(teacherInstance != 0){
                log.info("true")
                realUserName = URLEncoder.encode(realUserName,'UTF-8')
                redirect(uri:"/cloud/j_spring_security_check?j_username=${realUserName}&j_password=${params.j_password}")
           }else{
                if (User.countByUsername(params.j_username) > 0) { 
                    return redirect(uri:"/cloud/j_spring_security_check?j_username=${URLEncoder.encode(params.j_username,'UTF-8')}&j_password=${params.j_password}")
                }
                log.info("false")
                flash.message = "没有此用户！请检查您的地址和所选学校名称！"
                render view: 'auth', model: [postUrl: params.postUrl,remoteUser:params.j_username]
           }
     }

    private School checkDomain(){
           // 根据子域名判断学校
        def subDomain = org.apache.commons.lang.StringUtils.substringBefore(request.getServerName() ,".")
        log.info("login.authBefore subDomain = ${subDomain}")
 
        if(subDomain){
           return School.findBySubDomain(subDomain) 
        } 
    }

    def success = {
        def user = authenticateService.userDomain()
//        log.info "login.success user.school.id == ${user instanceof Teacher}"
        if (user in Teacher) { 
            user.refresh()
            log.info "login.success user.school.id == ${user.school.id}"
            session.schoolId = user.school.id
            session.school = user.school
        } 
//         这里不需要把schoolid放在session中，可以通过这种方式获得school id
//        def user = authenticateService?.userDomain()
//        user.refresh()

        redirect uri: '/layout/welcome' 
      }

	/**
	 * Show the login page.
	 */
	def auth = {
        if(!checkDomain()){
            //log.info("zeizeizei"+grailsApplication.config.grails.serverURL)
            //return redirect(url:"${grailsApplication.config.grails.serverURL}")
//            return redirect (url:grailsApplication.config.grails.serverURL)
        }
        nocache response
        if (isLoggedIn()) {
          redirect uri: '/'
        }
        String view
        String postUrl
        def config = authenticateService.securityConfig.security

        view = 'auth'
        postUrl = "${request.contextPath}${config.filterProcessesUrl}"

        // 根据子域名判断学校
        def school = checkDomain()
        render view: view, model: [postUrl: postUrl,remoteUser:params.remoteUser , school : school]
   }

	 
	// Login page (function|json) for Ajax access.
	def authAjax = {
		nocache(response)
		//this is example:
		render """
		<script type='text/javascript'>
		(function() {
			loginForm();
		})();
		</script>
		"""
	}

	/**
	 * The Ajax success redirect url.
	 */
	def ajaxSuccess = {
		nocache(response)
		render '{success: true}'
	}

	/**
	 * Show denied page.
	 */
	def denied = {
		if (isLoggedIn() && authenticationTrustResolver.isRememberMe(SCH.context?.authentication)) {
			// have cookie but the page is guarded with IS_AUTHENTICATED_FULLY
			redirect action: full, params: params
		}
	}

	/**
	 * Login page for users with a remember-me cookie but accessing a IS_AUTHENTICATED_FULLY page.
	 */
	def full = {
		render view: 'auth', params: params,
			model: [hasCookie: authenticationTrustResolver.isRememberMe(SCH.context?.authentication)]
	}

	// Denial page (data|view|json) for Ajax access.
	def deniedAjax = {
		//this is example:
		render "{error: 'access denied'}"
	}

	/**
	 * login failed
	 */
	def authfail = {

		def username = session[AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY]
		def msg = ''
		def exception = session[AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY]
		if (exception) {
			if (exception instanceof DisabledException) {
				msg = "[${username.substring(0,username.indexOf(grailsApplication.config.grails.default.username.segment))}] 已经停用！"
			}
			else {
				msg = "用户名或者密码错误，请重新登录！"
			}
		}

		if (isAjax()) {
			render "{error: '${msg}'}"
		}
		else {
			flash.message = msg
			redirect action: auth, params: params
		}
	}

	/**
	 * Check if logged in.
	 */
	private boolean isLoggedIn() {
		return authenticateService.isLoggedIn()
	}

	private boolean isAjax() {
		return authenticateService.isAjax(request)
	}

	/** cache controls */
	private void nocache(response) {
		response.setHeader('Cache-Control', 'no-cache') // HTTP 1.1
		response.addDateHeader('Expires', 0)
		response.setDateHeader('max-age', 0)
		response.setIntHeader ('Expires', -1) //prevents caching at the proxy server
		response.addHeader('cache-Control', 'private') //IE5.x only
	}
}
